package com.dxf.securitys.imagecode;


import com.dxf.common.utils.GlobalConstant;
import com.dxf.securitys.security.MyAuthenticationFailureHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description: 验证码过滤器（因为和自定义登陆验证有获取json数据的冲突所以没有应用）
 */
@Component
@Slf4j
public class CaptchaCodeFilter extends OncePerRequestFilter {

    @Resource
    MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    /**
     *对登陆请求中的验证码验证拦截
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        if(StringUtils.equals("/admin/login",request.getServletPath())
                && StringUtils.equalsIgnoreCase(request.getMethod(),"post")){
            try{
                //验证谜底与用户输入是否匹配
                validate(new ServletWebRequest(request));
            }catch(AuthenticationException e){
                myAuthenticationFailureHandler.onAuthenticationFailure(
                        request,response,e
                );
                return;
            }
        }

        filterChain.doFilter(request,response);

    }

    /**
     *验证码校验
     */
    private void validate(ServletWebRequest request) throws ServletRequestBindingException, IOException {
        //session对象
        HttpSession session = request.getRequest().getSession();
        //获取提交的验证码参数
        String codeInRequest = ServletRequestUtils.getStringParameter(
                request.getRequest(),GlobalConstant.CAPTCHA_IMG);

        if(StringUtils.isEmpty(codeInRequest)){
            throw new SessionAuthenticationException("验证码不能为空");
        }

        // 3. 获取session池中的验证码谜底
        CaptchaCode codeInSession = (CaptchaCode)
                session.getAttribute(GlobalConstant.CAPTCHA_SESSION_KEY);
        if(Objects.isNull(codeInSession)) {
            throw new SessionAuthenticationException("验证码不存在");
        }

        // 4. 校验服务器session池中的验证码是否过期
        if(codeInSession.isExpired()) {
            session.removeAttribute(GlobalConstant.CAPTCHA_SESSION_KEY);
            throw new SessionAuthenticationException("验证码已经过期");
        }

        // 5. 请求验证码校验
        if(!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new SessionAuthenticationException("验证码不匹配");
        }
        session.removeAttribute(GlobalConstant.CAPTCHA_SESSION_KEY);
    }


}

